package com.example.shopping.controller;

import com.example.shopping.pojo.Content;
import com.example.shopping.service.ContentService;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

/*
Create by 苍狼 于 2020/1/16
站在巅峰看世界，
落在深渊思人生。
*/
@Controller
@CrossOrigin
public class ContentController {
    @Autowired(required = false)
    private ContentService contentService;

    //全部查询广告信息
    @RequestMapping("/selectContentList")
    public String selectContentList(HttpServletRequest request) {
        List<Content> contents = contentService.selectContentList();
        request.getSession().setAttribute("contents", contents);
        return "content";
    }

    //广告类型新增
    @RequestMapping("/insertContent")
    public String insertContent(HttpServletRequest request, Content content) {
        Configuration cfg = new Configuration(Region.autoRegion());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "prgtQTHPRPcfhZyW7w_lhtXVvxDH5oUvp5XzeijH";
        String secretKey = "YUwe7-9aAIwv4T2cwqWGzF0vU4-e-miBMyT2SQh2";
        String bucket = "pinyougou-litao";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        try {
            byte[] uploadBytes = content.getPic().getBytes();
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                //上传完成之后返回的图片的hashcode值，可以用来存入数据库中的pic字段
                System.out.println(putRet.key);
                //两者同理
                System.out.println(putRet.hash);
                String pname = putRet.key;
                //设置为数据库中pic的值
                content.setPic(pname);
                content.setUrl("http://q59nafw97.bkt.clouddn.com/" + pname);
                //调用新增方法，进行新增
                System.out.println(pname);
                int i = contentService.insertContent(content);
                if (i > 0) {
                    return "redirect:selectContentList";
                }
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } finally {

        }
        return "redirect:insertContent";
    }


    //修改广告
    @RequestMapping("/updateContent")
    public String updateContent(Content content) {
        //修改时调用删除七牛元之后再进行新增，依旧需要先进行查询之后，再进行新增
        int i = contentService.updateContent(content);
        Content content1 = contentService.selectContentByIdOne(content.getId());

        Configuration cfg = new Configuration(Region.autoRegion());
        //...其他参数参考类注释
        String accessKey = "prgtQTHPRPcfhZyW7w_lhtXVvxDH5oUvp5XzeijH";
        String secretKey = "YUwe7-9aAIwv4T2cwqWGzF0vU4-e-miBMyT2SQh2";
        String bucket = "pinyougou-litao";
        String key = content1.getPic();
        ;
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, key);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }

        if (i > 0) {
            return "redirect:selectContentList";
        }
        return "redirect:updateContent";
    }

    //删除
    @RequestMapping("/deleteContentById")
    public String deleteContentById(int id) {
        //查询到对象之后，进行调用七牛云的删除方法
        Content content = contentService.selectContentByIdOne(id);
        //七牛云删除之后，调用service的方法进行删除
        Configuration cfg = new Configuration(Region.autoRegion());
        //...其他参数参考类注释
        String accessKey = "prgtQTHPRPcfhZyW7w_lhtXVvxDH5oUvp5XzeijH";
        String secretKey = "YUwe7-9aAIwv4T2cwqWGzF0vU4-e-miBMyT2SQh2";
        String bucket = "pinyougou-litao";
        String key = content.getPic().toString();
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, key);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());

        }
        int i = contentService.deleteContentById(id);
        if (i > 0) {
            return "redirect:selectContentList";
        }
        return "redirect:deleteContentById";
    }

    //修改广告状态为关闭
    @RequestMapping("/updateContentStatusClose")
    public String updateContentStatusClose(int id) {
        contentService.updateContentStatusClose(id);
        return "redirect:content";
    }

    //修改广告状态为开启
    @RequestMapping("/updateContentStatusOpen")
    public String updateContentStatusOpen(int id) {
        contentService.updateContentStatusOpen(id);
        return "redirect:content";
    }

    public void addQiniuyun(Content content) {
        Configuration cfg = new Configuration(Region.autoRegion());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "prgtQTHPRPcfhZyW7w_lhtXVvxDH5oUvp5XzeijH";
        String secretKey = "YUwe7-9aAIwv4T2cwqWGzF0vU4-e-miBMyT2SQh2";
        String bucket = "pinyougou-litao";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        try {
            byte[] uploadBytes = content.getPic().getBytes();
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                //上传完成之后返回的图片的hashcode值，可以用来存入数据库中的pic字段
                System.out.println(putRet.key);
                //两者同理
                System.out.println(putRet.hash);
                String pname = putRet.key;
                //设置为数据库中pic的值
                content.setPic(pname);
                content.setUrl("http://q59nafw97.bkt.clouddn.com/" + pname);
                //调用新增方法，进行新增
                System.out.println(pname);
            } catch (QiniuException ex) {
                //如果遇到异常，说明删除失败
                System.err.println(ex.code());
                System.err.println(ex.response.toString());

            }


        } finally {

        }
    }
}
